package com.yao.springcloud;

import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePropertySource;

/**
 * 
 * 获取 serviceConfig配置
 * @author liaohongjian
 *
 * @since 2017年3月27日
 *
 * @version 1.0
 */
public class ServiceConfigHelper extends PropertyPlaceholderConfigurer{
	
	private static final String ENCODING = "UTF-8";
	
//	private static final String ServiceConfigClassPath = "classpath:config/*.properties";
	private static final String ServiceConfigClassPath = "file:/E:\\sts_workspace\\config-server\\module-base-test.properties";
	
	//默认的系统属性文件
	private static final String applicationProperties = "classpath:application.properties";
	
	private static final Properties properties = new Properties();

	static {
		initServiceConfig();
	}
	
	/**
	 * 初始化服务配置文件
	 * @return
	 */
	private static void initServiceConfig(){
	    try {
	    	PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	    	
	    	//Config 
	    	Resource [] resourceList = resolver.getResources(ServiceConfigClassPath);
	    	
	    	for(Resource resource : resourceList){
	    		read(resource);
	    	}
	    	
	    	//读取application.properties文件
	    	read(resolver.getResource(applicationProperties));
	    	
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	/**
	 * 读取配置文件
	 * 
	 * @author liaohongjian
	 * @since 2017年8月22日
	 * @param resource
	 * @throws IOException
	 */
	private static void read(Resource resource) throws IOException{
		if(resource != null) {
			ResourcePropertySource config = new ResourcePropertySource(new EncodedResource(resource, ENCODING));
			
			String[] names = config.getPropertyNames();
			
			for(String key : names ){
				properties.put(key, config.getProperty(key));
			}
		}
	}
	
	/**
	 * 获取属性配置
	 * @param key
	 * @return
	 */
	public static String getServiceConfigValue(String key){
		
		Object value = properties.getProperty(key);
		
		return value == null ? null : value.toString().trim();
	}
	
	
	public static void main(String[] args) {
		Object value = properties.getProperty("logger");
		System.out.println("============"+value);
	}
}
